#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "kbsnewsrx.h"
#include "kbsconstants.h"
#include "checkdialog.h"
#include "settingdialog.h"
#include "settings.h"

#include <iostream>
#include <QRegExp>
#include <QMessageBox>
#include <QFileDialog>
#include <QtGlobal>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->seekSlider->setMediaObject(ui->videoPlayer->mediaObject());

    QObject::connect(ui->videoPlayer, SIGNAL(finished()), this, SLOT(videoPlayerFinished()));

    progressDialog = new DownloadProgressDialog(this);
    progressDialog->setModal(true);

    settingDialog = new SettingDialog(this);

    m_modified = false;
    
    /*vwidget = new Phonon::VideoWidget(ui->videoWidget);
    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->addWidget(vwidget);
    ui->videoWidget->setLayout(vLayout);*/
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionAbout_triggered()
{
    QString infotext = SETTING_APPLICATION;
    infotext.append(" ");
    infotext.append(VERSION);
    infotext.append("\n");
    infotext.append(tr("News Listerning Trainer\n"));
    infotext.append(tr("Copyright 2010 Yu-Chun Wang\nThis software is under General Public License version 2."));

    QMessageBox::about(this, tr("About"), infotext);
}

void MainWindow::on_playButton_clicked()
{
    if (ui->videoPlayer->isPlaying())
        return;

    /*ui->videoPlayer->load(Phonon::MediaSource("/home/mainlander/demo/20100125-70_2.asf"));
    ui->seekSlider->setMediaObject(ui->videoPlayer->mediaObject());
    ui->videoPlayer->play();*/

    if (dfile.mmsUrl() != "") {
        if (ui->videoPlayer->isPaused()) {
            ui->videoPlayer->play();
        }
        else {
            //ui->videoPlayer->play(QUrl(currentMMSUrl));
            if (dfile.localAsfPath() != "") {
                Phonon::MediaSource source(dfile.localAsfPath());
                ui->videoPlayer->load(source);
            }
            else {
                Phonon::MediaSource source(QUrl(dfile.mmsUrl()));
                ui->videoPlayer->load(source);
            }

            ui->videoPlayer->play();
        }
    }
    //ui->videoPlayer->play(QUrl("mms://newsvod.kbs.co.kr/news/news12/2010/01/21/20.asf"));
    /*Phonon::MediaObject *media = new Phonon::MediaObject;
    media->setCurrentSource(Phonon::MediaSource(QUrl("mms://newsvod.kbs.co.kr/news/news12/2010/01/21/20.asf")));

    Phonon::createPath(media, vwidget);
    vwidget->setAspectRatio(Phonon::VideoWidget::AspectRatioAuto);
    Phonon::AudioOutput *aOutput = new Phonon::AudioOutput(Phonon::VideoCategory);
    Phonon::createPath(media, aOutput);

    media->play();*/
}

void MainWindow::on_pauseButton_clicked()
{
    if (ui->videoPlayer->isPlaying()) {
        ui->videoPlayer->pause();
    }
    else if (ui->videoPlayer->isPaused()) {
        ui->videoPlayer->play();
    }
}

void MainWindow::on_actionUpdate_News_triggered()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(boardIndexReplyFinished(QNetworkReply*)));

    progressDialog->setValue(0);
    progressDialog->show();

    QString boardURL = KBS_NEWS_9_BOARD_INDEX_URL;
    if (ui->newsPlazaRadioButton->isChecked())
        boardURL = KBS_NEWS_PLAZA_BOARD_INDEX_URL;
    else if (ui->newsTimeRadioButton->isChecked())
        boardURL = KBS_NEWS_TIME_BOARD_INDEX_URL;
    else if (ui->sports9RadioButton->isChecked())
        boardURL = KBS_NEWS_SPORTS_9_BOARD_INDEX_URL;

    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(boardURL)));
    QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError)));
    QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64)));
}

void MainWindow::boardIndexReplyFinished(QNetworkReply *reply) {
    QByteArray data = reply->readAll();
    QString datastr = QString::fromUtf8(data, data.size());

    QStandardItemModel *model = parseBoardIndex(datastr, this);

    QItemSelectionModel *oldModel = ui->newsItemListView->selectionModel();
    ui->newsItemListView->setModel(model);
    ui->newsItemListView->setModelColumn(0);
    delete oldModel;

    reply->deleteLater();

    progressDialog->hide();
}

//void MainWindow::on_newsItemListView_clicked(QModelIndex index)
//{
    /*QModelIndex urlIndex = index.sibling(index.row(), 1);

    QString newsurl = index.model()->data(urlIndex, Qt::DisplayRole).toString();

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(contentReplyFinished(QNetworkReply*)));

    progressDialog->setValue(0);
    progressDialog->show();

    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(newsurl)));
    QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError)));
    QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64)));

    ui->newsTitleLabel->setText(index.model()->data(index, Qt::DisplayRole).toString());
    ui->scriptTextEdit->setText("");*/
//}

void MainWindow::contentReplyFinished(QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    QString datastr = QString::fromUtf8(data, data.size());

    QString currentMMSUrl = parseNewsContentMMS(datastr);

    dfile.setMmsURL(currentMMSUrl);

    std::cout << currentMMSUrl.toUtf8().data() << std::endl << std::flush;

    QString currentTranscript = parseNewsContentScript(datastr);
    //ui->scriptTextEdit->setText(parseNewsContentScript(datastr));

    dfile.setTranscript(currentTranscript);

    reply->deleteLater();

    progressDialog->hide();
}

void MainWindow::replyError(QNetworkReply::NetworkError error)
{
    std::cerr << "Network Error." << error << "\n";
}

void MainWindow::updateProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    if (progressDialog != 0) {
        int curValue = (bytesReceived * 100) / bytesTotal;
        progressDialog->setValue(curValue);
    }
}

/*
void MainWindow::on_actionShow_Transcript_triggered()
{
    ui->scriptTextEdit->setText(dfile.transcript());
}

void MainWindow::on_actionHide_Transcript_triggered()
{
    ui->scriptTextEdit->setText("");
}
*/

void MainWindow::on_actionCheck_Answer_triggered()
{
    CheckDialog dialog(this);
    QStringList list1;
    QStringList list2;

    list1 = parseNewsTranscript(dfile.transcript());
    list2 = parseNewsTranscript(ui->scriptTextEdit->toPlainText());

    dialog.setTranscript(list1);
    dialog.setAnswer(list2);
    dialog.performChecking();
    dialog.exec();
}

void MainWindow::on_selectNewsButton_clicked()
{
    if (!ui->newsItemListView->selectionModel())
        return;
    if (ui->newsItemListView->selectionModel()->selectedIndexes().count() <= 0)
        return;

    if (m_modified) {
        QMessageBox::StandardButton button = QMessageBox::question(this, tr("File is unsaved"), tr("Do you want to save current dictation?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if (button == QMessageBox::Yes) {
            this->on_actionSave_triggered();
        }
    }

    dfile.reset();

    QModelIndex index = ui->newsItemListView->selectionModel()->selectedIndexes().at(0);
    QModelIndex urlIndex = index.sibling(index.row(), 1);

    QString newsurl = index.model()->data(urlIndex, Qt::DisplayRole).toString();

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(contentReplyFinished(QNetworkReply*)));

    progressDialog->setValue(0);
    progressDialog->show();

    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(newsurl)));
    QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError)));
    QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64)));

    dfile.setTitle(index.model()->data(index, Qt::DisplayRole).toString());

    ui->newsTitleLabel->setText(dfile.title());
    ui->scriptTextEdit->setText("");

    m_modified = true;
}

void MainWindow::on_downloadAsfButton_clicked()
{
    QString mmsUrl = dfile.mmsUrl();
    if (mmsUrl == "")
        return;

    QSettings settings(QSettings::IniFormat, QSettings::UserScope, SETTING_ORGANIZATION, SETTING_APPLICATION);

    QString videoDir = settings.value(INI_KEY_VIDEO_DIRECTORY, QDir::homePath()).toString();
    if (!videoDir.endsWith("/"))
        videoDir.append("/");
    QString outFilePath = QDir::toNativeSeparators(videoDir + getFileNameFromMmsUrl(mmsUrl));
    dfile.setLocalAsfPath(outFilePath);

    QString program = settings.value(INI_KEY_MPLAYER_COMMAND, DEFAULT_MPLAYER_COMMAND).toString();

    QProcess *process = new QProcess(this);
    QStringList arguments;

#ifdef Q_OS_WIN32
    process->setWorkingDirectory(QDir::currentPath());
#endif

    arguments << "-dumpfile" << outFilePath << "-dumpstream" << mmsUrl;

    QObject::connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(downloadProcessFinished(int,QProcess::ExitStatus)));
    process->start(program, arguments);

    ui->statusBar->showMessage(tr("Start to download MMS stream"), 3000);
}

void MainWindow::downloadProcessFinished(int exitCode, QProcess::ExitStatus status)
{
    if (exitCode == 0 && status == QProcess::NormalExit)
        QMessageBox::information(this, tr("Donwload"), tr("MMS stream downloading completed."));
    else
        QMessageBox::critical(this, tr("Downlaod"), tr("MMS stream downloading failed."));
}

void MainWindow::on_actionSave_triggered()
{
    QString name = dfile.filePath();
    if (dfile.isUnSaved()) {
        QString suggestName = getFileNameFromMmsUrl(dfile.mmsUrl()).replace(".asf", ".klx");
        name = QFileDialog::getSaveFileName(this, tr("Save File"), QDir::home().filePath(suggestName), tr("Akarnaya Files (*.klx)"));
    }

    if (name != "") {
        QString answer = ui->scriptTextEdit->toPlainText();
        dfile.setAnswer(answer);
        dfile.saveXmlFilePath(name);
    }
}

void MainWindow::on_actionQuit_triggered()
{
    QApplication::quit();
}

void MainWindow::on_actionOpen_File_triggered()
{
    if (m_modified) {
        QMessageBox::StandardButton button = QMessageBox::question(this, tr("File is unsaved"), tr("Do you want to save current dictation?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        if (button == QMessageBox::Yes) {
            this->on_actionSave_triggered();
        }
    }

    dfile.reset();

    QString name = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::homePath(), tr("Akarnaya Files (*.klx)"));

    if (name != "")
        dfile.loadXmlFilePath(name);

    ui->newsTitleLabel->setText(dfile.title());
    ui->scriptTextEdit->setText(dfile.answer());
}

void MainWindow::on_actionPreferences_triggered()
{
    settingDialog->show();
}

void MainWindow::on_actionPlay_triggered()
{
    this->on_playButton_clicked();
}

void MainWindow::on_actionPause_triggered()
{
    this->on_pauseButton_clicked();
}

void MainWindow::on_actionStop_triggered()
{
    ui->videoPlayer->stop();
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    QMessageBox::aboutQt(this, tr("About Qt"));
}

void MainWindow::on_scriptTextEdit_textChanged()
{
    m_modified = true;
}

void MainWindow::videoPlayerFinished()
{
    ui->videoPlayer->stop();
    if (ui->repeatButton->isChecked()) {
        this->on_playButton_clicked();
    }
}
